<template>
  <div class="citychoose">

    <div class="wrapper">
      <div class="search">
        <div class="inner">
          <img class="icon" src="/static/imgs/search_grey.png">
          <input v-model="inputText"
                 placeholder='搜索城市' 
                 maxlength='20' 
                 confirm-type='搜索'
                 @input='inputFilter'
                 @confirm='inputFilter'
                 @focus='inputFilter'
          >
        </div>
        <div class="cancel" @click="clear">清空</div>
      </div>
    </div>

    <scroll-view scroll-y class="cities" :scroll-into-view="toView">
      <div v-for="(items,key) of showItems" :key="key" :id="key">
        <div class="key">{{key}}</div>
        <div class="values">
          <div class="value"
               v-for="item of items" 
               :key="index" 
               hover-class="hover"
               :data-item="item.name"
               @click="choose"
          >
            {{item.name}}
          </div>
        </div>
      </div>
    </scroll-view>

    <!-- <div id="alphabet">
      <div class="key" 
           v-for="(items,key) of showItems" 
           :key="key"
           @click="handleLetterClick"
           @touchstart.stop="handleTouchStart"
           @touchmove="handleTouchMove"
           @touchend="handleTouchEnd"
      >
        {{key}}
      </div>
    </div> -->

    <div class="empty" v-if="!showItems">暂无城市可以选择</div>
  </div>
</template>

<script type="text/ecmascript-6">
import StaticData from "@/data/staticData";
import { isEmptyObject } from "@/utils/utils";

export default {
  data() {
    return {
      inputText: "",
      cities: [],
      showItems: [],
      touchStatus: false,
      timer: null,
      startY: 0,
      currentIndex: 0,
      toView: ''
    };
  },
  mounted() {
    let cities = this.getSortedAreaObj(StaticData || []);
    this.cities = cities;
    this.showItems = cities;
    // this.getstartY();
  },
  methods: {
    // 按照字母顺序生成需要的数据格式
    getSortedAreaObj(a) {
      let data = a.cities;
      data = data.sort((a, b) => {
        if (a.letter < b.letter) return -1;
        if (a.letter > b.letter) return 1;
        return 0;
      });

      let obj = {};
      for (let item of data) {
        let letter = item.letter;
        if (!obj[letter]) obj[letter] = [];
        obj[letter].push(item);
      }
      return obj;
    },

    // 选择城市
    inputFilter(e) {
      const value = e.target.value.replace(/\s+/g, "");
      const cities = this.cities;
      let showItems = {};

      if (value.length) {
        for (let i in cities) {
          let items = cities[i];
          items.forEach(item => {
            if (item.name.indexOf(value) !== -1) {
              if (isEmptyObject(showItems[i])) {
                showItems[i] = [];
              }
              showItems[i].push(item);
            }
          });
        }
        if (isEmptyObject(showItems)) {
          showItems = null;
        }
        this.showItems = showItems;
      } else {
        (this.showItems = cities), (this.emptyCity = false);
      }
    },

    // 清空搜索
    clear() {
      this.inputText = "";
      this.showItems = this.cities;
    },

    // 选中跳转
    choose(e) {
      const cName = e.currentTarget.dataset.item;
      const page = getCurrentPages();
      const homeP = page[page.length - 2];

      homeP.data.searchText = cName;
      homeP.data.cityChanged = true;
      wx.navigateBack();
    },

    // 获取字母A距离顶部的位置
    getstartY() {
      const alphabet = wx.createSelectorQuery().select("#alphabet");
      const that = this
      alphabet
        .boundingClientRect(function(res) {
          that.startY = res.top*2;
        })
        .exec();
    },

    // 字母表拖动功能
    handleTouchStart() {
      // 点击事件状态
      this.touchStatus = true;
    },

    handleTouchMove(e) {
      if (this.touchStatus) {
        // 创建截流
        if (this.timer) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
          // 获取手指移动时距离顶部的值
          const touchY = e.clientY
          // 获取每个字母的索引值，差值除以每个字母的高度
          const index = Math.floor((touchY - this.startY) / 20);

          // 将值传给父
          if (index >= 0 && index <= Object.keys(this.showItems).length) {
            this.toView = Object.keys(this.showItems)[index]
          }
        }, 160);
      }
    },

    handleTouchEnd() {
      this.touchStatus = false;
    }
  }
};
</script>

<style lang="scss" scoped>
.citychoose {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f2f2f2;
  .wrapper {
    font-size: 0;
    background: #fff;
    padding: 30rpx;
    position: relative;
    border-bottom: 1rpx solid #e6e6e6;
    height: 128rpx;
    box-sizing: border-box;
    .search {
      display: flex;
      justify-content: flex-start;
      align-items: center;
      .inner {
        background: #efefef;
        font-size: 30rpx;
        padding: 16rpx 0 16rpx 20rpx;
        box-sizing: border-box;
        border-radius: 8rpx;
        flex: 1;
        display: flex;
        align-items: center;
        .icon {
          width: 28rpx;
          height: 28rpx;
          margin-right: 10rpx;
        }
        input {
          background: #efefef;
          font-size: 30rpx;
          height: 38rpx;
          /* 覆盖默认样式 min-height */
          min-height: 38rpx;
          line-height: 38rpx;
          width: 100%;
          box-sizing: border-box;
        }
      }
      .cancel {
        font-size: 30rpx;
        display: inline-block;
        color: #666;
        width: 2.5em;
        text-align: right;
      }
    }
  }
  .cities {
    // height: 1078rpx;
    font-size: 32rpx;
    color: #333;
    background: #fff;
    .key {
      background: #f2f2f2;
      height: 50rpx;
      display: flex;
      align-items: center;
      padding: 0 30rpx;
    }
    .values {
      .value {
        border-bottom: 1rpx solid #efefef;
        height: 104rpx;
        display: flex;
        align-items: center;
        padding: 0 30rpx;
        &:last-child {
          border-bottom: none;
        }
      }
      .hover {
        background: #efefef;
      }
    }
  }
  // #alphabet {
  //   display: flex;
  //   flex-direction: column;
  //   justify-content: center;
  //   position: fixed;
  //   top: 100rpx;
  //   right: 0;
  //   bottom: 0;
  //   width: 50rpx;
  //   font-size: 30rpx;
  //   .key {
  //     line-height: 40rpx;
  //     text-align: center;
  //     color: #000;
  //   }
  // }
  .empty {
    margin-top: 100rpx;
    font-size: 30rpx;
    text-align: center;
    color: #666;
  }
}
</style>
